package cn.sofwin.blog.web;


import cn.sofwin.blog.entity.Article;
import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.ArticleService;
import cn.sofwin.blog.service.impl.ArticleServiceImpl;
import cn.sofwin.blog.utils.HttpHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文章删除Servlet
 * @author ZX
 * @version 1.0
 */
@WebServlet("/blog/article/remove")
public class ArticleRemoveServlet extends HttpServlet {

    /** 文章服务接口 */
    private ArticleService articleService = ArticleServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if(StringUtils.isBlank(id)){
            HttpHelper.error("参数错误", req, resp);
        }else{
            Integer aid = Integer.valueOf(id);
            User user = (User) req.getSession().getAttribute("LOGIN_USER");
            Article article = articleService.get(aid);
            if(article == null || ( !user.getId().equals(article.getUser().getId()) )){
                HttpHelper.error("没有权限", req, resp);
            }else{
                articleService.remove(aid);
                // 重定向到首页
                resp.sendRedirect("/index");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
